// pages/account/report/report-detail.js
import * as echarts from '../../../components/ec-canvas/echarts';


const app = getApp()
const { wxPost, wxGet, commonShare, imgHost, numFormat } = require('../../../utils/common.js')
var pieCharPlan = null
var gaugeChart = null


Page({

  data: {
    reportId: '',
    waitLoading: true,
    guideShow: true,
    homeShow: false, 
    isQuarter:false,
    imgHost,
    ecPlan: {
      onInit: function(canvas, width, height, dpr) {
        pieCharPlan = echarts.init(canvas, null, {
          width: width,
          height: height,
          devicePixelRatio: dpr // new
        });
        canvas.setChart(pieCharPlan)
        return pieCharPlan
      }
    },
    gaugeChartEc: {
      onInit: function(canvas, width, height, dpr) {
        gaugeChart = echarts.init(canvas, null, {
          width: width,
          height: height,
          devicePixelRatio: dpr // new
        });
        canvas.setChart(gaugeChart)
        return gaugeChart
      }
    }
  },
  viewImgs(e){
    const {reportImg,imgHost} =this.data
    const {index}=e.currentTarget.dataset
    if(reportImg){
      let imgs=[]
      let {img1FileKey,img2FileKey,img3FileKey}=reportImg||{}
      if(img1FileKey)  imgs.push(imgHost+'/'+img1FileKey)
      if(img2FileKey)  imgs.push(imgHost+'/'+img2FileKey)
      if(img3FileKey)  imgs.push(imgHost+'/'+img3FileKey)
      wx.previewImage({
        urls: imgs,
        current:imgs[index]
      })
    }
   
  },
  tabSelect: function () {
    if (!this.data.guideShow) {
      this.setData({
        guideShow: true,
        homeShow: false
      })
    } else {
      this.setData({
        guideShow: false,
        homeShow: true
      })
    }
  },
  onLoad: function (options) {
    const { reportId ,type} = options
    this.setData({ reportId, infoId: options.infoId || '',type:type||'',isQuarter:type==='quarter'})
    setTimeout(() => {
      this.loadReportDetail(reportId)
    }, 100);
    //this.loadReportDetail(reportId)
  },
  loadReportDetail(reportId){
    if (reportId){
      const {  infoId,type } = this.data
      wx.showLoading({
        title: '数据加载中...',
        mask: true
      })
      wxGet('/assetsInfo/reportInfo', { reportId, infoId,type }, ({ data }) => {
        if (data && data['errorCode'] === 0) {
          const { report ,communicateList,reportImg} = data
          let list1 = []
          let list2 = []
          let list3 = []
          let list4 = []
          if(data['refresh']==='Y'){
            var pages = getCurrentPages()
            var prevPage = pages[pages.length - 2] //上一个页面
            if (prevPage) {
              prevPage.loadList()
            }
          }

          report && report['dealRecords'].forEach(o => {
            let fund = o['fundId'] || {}
            if (fund['assetType'] === '权益类') {
              list1.push(o)
            } else if (fund['assetType'] === '债类+衍生品类') {
              list2.push(o)
            } else if (fund['assetType']==='现金类'){
              if (o.cost && o.mkv) {
                list3.push(o)
              }
            }
            o.portion = o.portion ? o.portion.toFixed(2) : o.portion

          })
          // let {
          //   planningCost, planningMkv, planningBalanceRatio,
          //   familyCost, familyMkv, familyBalanceRatio,
          // } = data['report']['incomeInfo']
          // list4.push({
          //   type: '新竹规划',
          //   cost: numFormat(planningCost < 0 ? 0 : planningCost || '--'),
          //   mkv: numFormat(planningMkv || '--'),
          //   ratio: planningBalanceRatio
          // })
          // list4.push({
          //   type: '家庭总计',
          //   cost: numFormat(familyCost < 0 ? 0 : familyCost || '--'),
          //   mkv: numFormat(familyMkv || '--'),
          //   ratio: familyBalanceRatio
          // })
          let {
            equityREITsAssetsTypeMkv, equityREITsAssetsTypeMkvRatio, equityREITsAssetsTypeBalanceRatio,
            debtAssetsTypeMkv, debtAssetsTypeMkvRatio, debtAssetsTypeBalanceRatio,
            cashAssetsTypeMkv, cashAssetsTypeMkvRatio, cashAssetsTypeBalanceRatio,
            planningCost,planningMkv, planningBalanceRatio
          } = report['incomeInfo']
          list4.push({
            type: '权益类',
            cost: numFormat(equityREITsAssetsTypeMkv < 0 ? 0 : equityREITsAssetsTypeMkv || '--'),
            mkv: equityREITsAssetsTypeMkvRatio,
            ratio: equityREITsAssetsTypeBalanceRatio
          })
          list4.push({
            type: '债类+衍生品类',
            cost: numFormat(debtAssetsTypeMkv < 0 ? 0 : debtAssetsTypeMkv || '--'),
            mkv: debtAssetsTypeMkvRatio,
            ratio: debtAssetsTypeBalanceRatio
          })
          list4.push({
            type: '现金类',
            cost: numFormat(cashAssetsTypeMkv < 0 ? 0 : cashAssetsTypeMkv || '--'),
            mkv: cashAssetsTypeMkvRatio,
            ratio: '--'
          })
          list4.push({
            type: '合计',
            cost: numFormat(planningMkv < 0 ? 0 : planningMkv || '--'),
            mkv: '100%',
            ratio: planningBalanceRatio
          })
          this.setData({  list1, list2,list3,list4, report,communicateList,reportImg })
          setTimeout(() => {
            this.drawPie( planningCost, equityREITsAssetsTypeMkv, debtAssetsTypeMkv, cashAssetsTypeMkv)
            this.drawGauge( parseFloat(planningBalanceRatio.replace('%', '')))

          }, 100)
        }
      }, null, () => {
        this.setData({   waitLoading: false})
        wx.hideLoading()
      })
    }
  },
  drawGauge ( ratio) {
    gaugeChart.setOption({
      tooltip: {
        formatter: '{a} <br/>{b} : {c}%'
      },
      series: [
        {
          // startAngle: 240, //开始角度 左侧角度
          // endAngle: 0, //结束角度 右侧
          min: -50,
          max: 100,
          radius: '100%',
          name: '收益率',
          type: 'gauge',
          axisLine: {            // 坐标轴线
            lineStyle: {       // 属性lineStyle控制线条样式
              color: [[0.3, 'dark'], [0.8, 'orange'], [1, 'brown']]
            }
          },
          detail: {
            formatter: '{value}%',
            fontSize:16
          },
          data: [{value: ratio, name: '收益率'}]
        }
      ]
    })
  },
  drawPie :function( cost, equityMkv, debtMkv, cashMkv) {
    const that=this
     pieCharPlan.setOption({
      tooltip: {
        trigger: 'axis',
        axisPointer: {            // 坐标轴指示器，坐标轴触发有效
          type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
        }
      },
      color: ['#f8ca4b', '#274189', '#e8968f', '#FF8096'],
      legend: {
        data: ['现金类', '债类+衍生品类', '权益类', '规划资金'],
        textStyle: {
          //fontSize: 26
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: ['规划资金', '现在市值']
      },
      yAxis: {
        type: 'value'
      },
      series: that.maskSeriesData(cost, equityMkv, debtMkv, cashMkv),
      label: {
        normal: {
          show: true,
          textStyle: {
           // fontSize: 26
          }
        },
        emphasis: {
          show: true
        }
      }
    })
  },
  maskSeriesData (cost, equityMkv, debtMkv, cashMkv) {
    const itemWidth=40
    return [{
      name: '现金类',
      type: 'bar',
      stack: '总量',
      barWidth: itemWidth,//柱图宽度
      label: {
        show: true,
        position: 'insideRight'
      },
      textStyle: {
       // fontSize: 26
      },
      data: [null, this.numChange(cashMkv || null)]
    },
      {
        name: '债类+衍生品类',
        type: 'bar',
        stack: '总量',
        barWidth: itemWidth,//柱图宽度
        label: {
          show: true,
          position: 'insideRight',
          textStyle: {
            //fontSize: 15
          }
        },
        data: [null, this.numChange(debtMkv || null)]
      }, {
        name: '权益类',
        type: 'bar',
        stack: '总量',
        barWidth: itemWidth,//柱图宽度
        label: {
          show: true,
          position: 'insideRight',
          textStyle: {
           // fontSize: 15
          }
        },
        data: [null, this.numChange(equityMkv || null)]
      },
      {
        name: '规划资金',
        type: 'bar',
        stack: '总量',
        barWidth: itemWidth,//柱图宽度
        label: {
          show: true,
          position: 'insideRight',
          textStyle: {
           // fontSize: 15
          }
        },
        data: [this.numChange(cost || null), null]
      }]
  },
  numChange (num) {
    if (isNaN(num) || !num) return num
    num = parseFloat(num)
    return (num / 10000).toFixed(2)
  },
  onShareAppMessage: function () {
    return commonShare()
  }
})